
package com.windgo.service;

import cn.hutool.core.util.RandomUtil;
import com.windgo.bean.MarketUser;
import com.windgo.bean.MarketUserExample;
import com.windgo.bean.common.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.windgo.bean.wxVo.UserInfoEntity;
import com.windgo.bean.wxVo.WxRegistPo;
import com.windgo.bean.wxVo.WxRegistVo;
import com.windgo.bean.wxVo.WxUserResetPo;
import com.windgo.config.AliyunComponent;
import com.windgo.mapper.MarketUserMapper;
import com.windgo.mapper.UserMapper;
import com.windgo.util.RegexUtils;
import com.windgo.utils.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.ServletContext;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * @author stone
 * @date 2022/06/25 11:11
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    ServletContext servletContext;

    // access-key-id:
    // access-key-secret:
    // oss:
    // bucket: cskaoyan
    // endPoint: oss-cn-beijing.aliyuncs.com
    // sms:
    // signName:     stone4j
    // templateCode: SMS_173765187
    @Autowired
    UserMapper userMapper;

    @Autowired
    MarketUserMapper marketUserMapper;

    /**
     * @param info     分页信息 分页：page\limit 排序: sort\order
     * @param username 用户名
     * @param mobile   手机号
     * @return com.windgo.bean.common.CommonData<com.windgo.bean.MarketUser>
     * @author mabai
     * @since 2022/10/12 21:29
     */
    @Override
    public CommonData<MarketUser> list(BasePageInfo info, String username, String mobile) {
        // 开启分页
        PageHelper.startPage(info.getPage(), info.getLimit());
        // 根据username或mobile做条件查询：sql语句为where username like ? and mobile = ?
        // 需要创建一个Example对象来拼接sql语句
        MarketUserExample example = new MarketUserExample();
        // 设置排序
        example.setOrderByClause(info.getSort() + " " + info.getOrder());// sort是表中的某个字段，order是排序方式
        MarketUserExample.Criteria criteria = example.createCriteria();
        // 判断username是否为空，username是模糊查询
        if (!StringUtil.isEmpty(username)) {
            criteria.andUsernameLike("%" + username + "%");
        }
        // 判断mobile是否为空，mobile是精准查询
        if (!StringUtil.isEmpty(mobile)) {
            criteria.andMobileEqualTo(mobile);
        }
        // 获取data对象里的list
        List<MarketUser> list = marketUserMapper.selectByExample(example);
        // 将获取到的User集合进行分页
        PageInfo<MarketUser> pageInfo = new PageInfo<>(list);
        return CommonData.data(pageInfo);
    }

    /**
     * 编辑会员信息
     * @param marketUser
     * @return
     */
    @Override
    public int updateUserInfo(MarketUser marketUser) {
        try {
            int count = marketUserMapper.updateByPrimaryKeySelective(marketUser);
            return 200;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }

    }

    /**
     * 最后登录时间和IP
     * @param marketUser
     */
    @Override
    public void updateLoginTimeAndIp(MarketUser marketUser) {
        try {
            marketUserMapper.updateByPrimaryKeySelective(marketUser);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送验证码
     * @param mobile
     */
    @Override
    public void regCaptcha(String mobile) {


        if (!RegexUtils.isPhoneInvalid(mobile)){
            try {

                String code = RandomUtil.randomNumbers(6);
                // Subject subject = SecurityUtils.getSubject();
                // Session session = subject.getSession();
               // session.setAttribute(mobile,code);


                AliyunComponent aliyunComponent = new AliyunComponent();
                aliyunComponent.sendMsg(mobile,code);
                System.out.println("验证码是: " + code);
                servletContext.setAttribute(mobile,code);
            } catch (InvalidSessionException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 注册
     * @param wxRegistVo
     * @return
     */
    @Override
    public int register(WxRegistPo wxRegistVo) {
        if (RegexUtils.isPhoneInvalid(wxRegistVo.getMobile())){
            return 707;
        }
        String username1 = wxRegistVo.getUsername();
        String username = userMapper.selectUserByUserName(username1);
        if (!StringUtil.isEmpty(username)){
            return 704;
        }
        String mobile = userMapper.selectUserByMobile(wxRegistVo.getMobile());
        if (!StringUtil.isEmpty(mobile)){
            return 705;
        }
        String code = (String) servletContext.getAttribute(wxRegistVo.getMobile());
        if (!code.equals(wxRegistVo.getCode())){
            return 703;
        }
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String addTime = simpleDateFormat.format(date);
        MarketUser marketUser = new MarketUser();
        marketUser.setMobile(wxRegistVo.getMobile());
        marketUser.setUsername(wxRegistVo.getUsername());
        marketUser.setPassword(wxRegistVo.getPassword());
        marketUser.setAvatar("https://yanxuan.nosdn.127.net/80841d741d7fa3073e0ae27bf487339f.jpg?imageView&quality=90&thumbnail=64x64");
        marketUser.setSessionKey("session_key_wo_zhen_bu_hui");
        marketUser.setWeixinOpenid("weixin_openid_wo_bu_hui");
        marketUser.setNickname(wxRegistVo.getUsername());
        marketUser.setAddTime(addTime);
        try {
            int count = userMapper.insertSelective(marketUser);
            return 200;
        } catch (Exception e) {
            e.printStackTrace();
            return 404;
        }



    }

    /**
     * wx_登录界面_用户注册
     * @param wxRegistVo
     * @return
     */
    @Override
    public WxRegistVo registerUser(WxRegistPo wxRegistVo) {
        UserInfoEntity wxRegistVo1 = userMapper.selectByUsername(wxRegistVo.getUsername());
        WxRegistVo wxRegistVo2 = new WxRegistVo();
        wxRegistVo2.setUserInfo(wxRegistVo1);
        wxRegistVo2.setToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0aGlzIGlzIG1hcmtldCB0b2tlbiIsImF1ZCI6Ik1JTklBUFAiLCJpc3MiOiJNQVJLRVQiLCJleHAiOjE2NjU5NzczMzAsInVzZXJJZCI6NTIsImlhdCI6MTY2NTk3MDEzMH0.aXOnRZzh0Z6YkGMggL3OoQSyg6WV1Y7SRI-dCXc7580");
        return wxRegistVo2;
    }

    /**
     * wx_登录界面_忘记密码
     * @param wxUserResetPo
     * @return
     */
    @Override
    public int resetUserInfo(WxUserResetPo wxUserResetPo) {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String code = (String) servletContext.getAttribute(wxUserResetPo.getMobile());
        int count = 0;
        if (wxUserResetPo.getCode().equals(code)){
            MarketUser marketUser = new MarketUser();
            marketUser.setPassword(wxUserResetPo.getPassword());
            marketUser.setMobile(wxUserResetPo.getMobile());
            marketUser.setUpdateTime(simpleDateFormat.format(date));
            count = userMapper.updateByMobileSelective(marketUser);
        }
        if (count == 1){
            return 200;
        }


        return 404;
    }


}

